<template>
  <div class="container">
    <div class="app-container">
      <el-tree v-loading="loading" :data="depts" :props="defaultProps" default-expand-all :expand-on-click-node="false">
        <template v-slot="{ data }">
          <el-row type="flex" justify="space-between" align="middle" style="width: 100%; height: 40px">
            <el-col><span>{{ data.name }}</span></el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>
              <el-dropdown @command="operateDept($event, data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 弹层 -->
    <dept-dialog ref="dialogRef" :show-dialog.sync="showDialog" :current-node-id="currentNodeId" @onSuccess="getDepartments" />
  </div>
</template>

<script>
import { deptDeleteDepartmentApi, deptGetDepartmentDetailApi, deptGetDepartmentsApi } from '@/api/department'
import { transListToTreeData } from '@/utils'
import DeptDialog from './components/DeptDialog.vue'

export default {
  name: 'Department',
  components: { DeptDialog },
  data() {
    return {
      showDialog: false,
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      currentNodeId: null,
      loading: false
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    /**
     * 获取部门列表
     */
    async getDepartments() {
      this.loading = true
      const res = await deptGetDepartmentsApi()
      this.depts = transListToTreeData(res, 0)
      this.loading = false
    },
    /**
     * 部门操作事件
     * @param type 操作类型
     * @param id 部门id
     */
    async operateDept(type, id) {
      if (type === 'add') {
        this.currentNodeId = id
        this.showDialog = true
      } else if (type === 'edit') {
        this.$refs.dialogRef.formData = await deptGetDepartmentDetailApi(id)
        this.showDialog = true
      } else {
        await this.$confirm('您确定删除该部门吗？', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deptDeleteDepartmentApi(id)
        this.$message.success('删除部门成功~')
        this.getDepartments()
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}

.tree-manager {
  width: 100px;
  display: inline-block;
  margin: 10px;
}
</style>
